package com.googlecode.sere.connectors.httpcomponents

import org.apache.http.message.BasicHeaderElementIterator
import com.googlecode.sere.util.Implicits._
import org.apache.http.{HttpEntityEnclosingRequest, HttpRequest => HttpRequestImpl}
import com.googlecode.sere.translation.{MediaType, AcceptedTypes, MediaRange}
import com.googlecode.sere.http.{HeaderElement, HttpRequest}
import org.apache.http.{HeaderElement => ApacheHeaderElement}

class HttpCoreRequest(private val impl: HttpRequestImpl) extends HttpRequest {

  def headerElements(name: String): Seq[HeaderElement] = {
    val it = new BasicHeaderElementIterator(impl.headerIterator(name))
      .asInstanceOf[java.util.Iterator[ApacheHeaderElement]]
    HttpCoreRequest.apacheHeaderToSereHeader(it.toIterable.toSeq)
  }

	lazy val method = impl.getRequestLine.getMethod.toLowerCase

	lazy val uri = impl.getRequestLine.getUri

  lazy val body = impl match {
      case enclosing: HttpEntityEnclosingRequest => new String(enclosing.getEntity.getContent.slurp)
      case _ => ""
  }
}

object HttpCoreRequest {

  def apacheHeaderToSereHeader(apacheHeader: Seq[ApacheHeaderElement]) = {
    apacheHeader map { e =>
      val params = e.getParameters map { p => (p.getName, p.getValue) }
      HeaderElement(e.getName, e.getValue, Map(params:_*))
    }
  }
}
